package cn.qlin.mvc.orm.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import cn.qlin.mvc.orm.QlinDB;
import cn.qlin.mvc.orm.bean.AutoKey;
import cn.qlin.mvc.orm.bean.Where;

public class KeyAuto {
	public static int getId(String tablename){
		int id = 0;
		synchronized (KeyAuto.class) {
			QlinDB db = new QlinDB();
			Where where = new Where();
			where.add("`skey`='"+tablename+"id'"); 
			List<Object> auto = db.query(AutoKey.class,where);
			if(auto.size()<1){
				AutoKey autokey = new AutoKey();
				autokey.setTablename(tablename+"id");
				autokey.setTableid("0");
				db.add(autokey);
			}
			AutoKey autokeytemp = (AutoKey) auto.get(0);
			id = Integer.parseInt(autokeytemp.getTableid());
			id++;
			autokeytemp.setTableid(id+"");
			db.update(autokeytemp);
		}
		return id;
	}
	public static int getId1(String tablename){
		int id = 0;
		synchronized (KeyAuto.class) {
			FileOutputStream out = null;
			BufferedReader bufferedReader = null;
			File file = new File("d:/"+tablename+"id"+".txt");
			if(!file.exists()){
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
				id = Integer.parseInt(bufferedReader.readLine());
				out = new FileOutputStream(file);
				id++;	
				out.write((id+"").getBytes());
				out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					out.close();
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return id;
	}
}
